package cloud

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"smart_home/api/models"
	"smart_home/api/xfyun/depots"
	"strings"
)

func init() {
	registerCloud("timing_switch", timing_switch)
}

/*
定时{time}{switch}{equipment}
定时{switch}{equipment}
定时{switch}{scene_name}{equipment}
*/
func timing_switch(rq *depots.Request, res *depots.XfyunResult, userParams *UserParams) {
	var (
		ok              bool
		sName           string
		err             error
		timSlot, eqSlot depots.RSlot
		eqNameSplits    []string
		eqs             []*models.Equipment
		eqParams        = make(map[string]interface{})
		actMsg          = rq.Request.Intents[0].Slots["switch"].Value
		answerStr       = "正在为您设置%s定时%s%s"
	)

	if len(userParams.Sta) > 0 {
		res.Data["sta"] = userParams.Sta
	}

	res.Data["act"] = false
	if actMsg == "开" || actMsg == "打开" || actMsg == "开启" || actMsg == "启动" {
		res.Data["act"] = true
	}

	// 询问定时时间
	if timSlot, ok = rq.Request.Intents[0].Slots["time"]; !ok {
		res.IsEnd = false
		res.IsHandle = false
		res.Slot = "time"
		res.Answer = "请指定定时时间"
		return
	}

	// 不指定设备名称
	if eqSlot, ok = rq.Request.Intents[0].Slots["equipment"]; !ok {
		// 无外放设备 直接操作当前设备
		if len(userParams.Sta) > 0 && userParams.DeviceType == 1 {
			res.Data["name"] = "设备"
			res.Answer = fmt.Sprintf(answerStr, timSlot.Value, actMsg, res.Data["name"])
			res.IsHandle = true
			return
		} else {
			// 询问槽位
			res.IsEnd = false
			res.Answer = "请指定需要操作的设备名称"
			res.Slot = "equipment"
			return
		}
	}

	// 解析设备名称和设备所在场景名称
	if _, ok = rq.Request.Intents[0].Slots["scene"]; ok {
		sName = rq.Request.Intents[0].Slots["scene"].Value
	}

	eqNameSplits = strings.Split(eqSlot.Value, "的")
	eqParams["name"] = eqNameSplits[0]
	if len(eqNameSplits) > 1 {
		sName = eqNameSplits[0]
		eqParams["name"] = eqNameSplits[1]
	}

	if eqs, err = models.GetAllEquipmentByUid(userParams.User.Id, 0, eqParams); err != nil {
		logs.Error("timing_switch err:", err)
		res.Answer = "系统发生错误，请再试一次吧"
		return
	}

	if eqs == nil {
		res.Answer = "您还没有智能设备，请到聆漆购买吧"
		return
	}

	// 如果指定场景
	if len(sName) > 0 && len(eqs) > 0 {
		for k, _ := range eqs {
			eqs = append(eqs[:k], eqs[k+1:]...)
		}
	}

	if len(eqs) == 0 {
		res.Answer = "您还没有智能设备，请到聆漆购买吧"
		return
	}

	if len(eqs) > 1 {
		res.Answer = fmt.Sprintf("发现%d个可操作设备,请指定%s所在区域", len(eqs), eqParams["name"])
		res.IsEnd = false
		res.Slot = "scene"
		return
	}

	res.Answer = fmt.Sprintf(answerStr, timSlot.Value, actMsg, eqParams["name"])
	res.IsHandle = true
	res.Data["name"] = eqNameSplits[0]
	res.Data["sta"] = eqs[0].Sta
}
